import { Edit, EditInfo, EditResponse, PhotoResponse, UserInfo, UserResponse } from '@/types/data.d.'
import request from '@/utils/request'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { AppThunk } from '../index'
// state变量类型
export interface userState {
  userInfo: UserInfo
  editInfo: EditInfo
}

export const user = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'user',
  // 1. 定义变量(状态数据)
  initialState: {
    userInfo: {},
    editInfo: {}
  } as userState,
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    setUserInfo(state, action: PayloadAction<UserInfo | undefined>) {
      state.userInfo = action.payload!
    },
    setEditInfo(state, action: PayloadAction<EditInfo | undefined>) {
      state.editInfo = action.payload!
    },
    // 修改 reducer 数据答达到修改edit数据
    editUserInfo(state, action: PayloadAction<Edit | undefined>) {
      // console.log('action.payload', action.payload)
      state.editInfo = {
        ...state.editInfo,
        ...action.payload!
      }
    },
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const { setUserInfo, setEditInfo, editUserInfo } = user.actions

// 3. 异步action
// 获取用户资料
export const getUserInfoAction = (payload?: unknown): AppThunk => {
  return async (dispatch, getState) => {
    const res: UserResponse = await request('/user')
    // console.log(res)
    dispatch(setUserInfo(res.data))
  }
}
// 获取用户信息
export const getEditInfoAction = (payload?: unknown): AppThunk => {
  return async (dispatch, getState) => {
    const res: EditResponse = await request('/user/profile')
    // console.log(res)
    dispatch(setEditInfo(res.data))
  }
}
// 修改用户信息
export const editUserInfoAction = (payload?: Edit): AppThunk => {
  return async (dispatch, getState) => {
    await request.patch('/user/profile', payload)
    dispatch(editUserInfo(payload))
  }
}
// 修改用户头像
export const editUserPhotoAction = (payload?: FormData): AppThunk => {
  return async (dispatch, getState) => {
    // console.log('payload', payload)
    const res: PhotoResponse = await request.patch('/user/photo', payload)
    dispatch(editUserInfo(res.data))
  }
}

// 导出reducer(创建store使用)
export default user.reducer